#include<stdio.h>
#include<windows.h>
#include<stdlib.h>
#include<time.h>

#define MAX 10000
#define BASE 10

void printArr(int *arr, int n) {
    int i;
    for (i = 0; i < n; i++) {
        printf("%d\t", arr[i]);
    }
}

void radixSort(int *arr, int start, int end) {
    int num = end - start;
    int i, exp = 1;
    int temp[num];
    int max = arr[start];

    for (i = start + 1; i <= end; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }

    while (max / exp > 0) {
        int bucket[BASE] = {0};

        for (i = start; i <= end; i++) {
            bucket[(int)(arr[i] / exp) % BASE]++;
        }

        for (i = 1; i < BASE; i++) {
            bucket[i] += bucket[i - 1];
        }

        for (i = end; i >= start; i--) {
            temp[--bucket[(int)(arr[i] / exp) % BASE]] = arr[i];
        }

        for (i = 0; i <= num; i++) {
            arr[start + i] = temp[i];
        }

        exp *= BASE;
    }
}

void swap(int *arr, int start, int end) {
    while(start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;

        start++;
        end--;
    }
}

void negativeRadixSort(int *arr, int start, int end) {
    for (int k = start; k <= end; k++) {
        arr[k] *= -1;
    }
    radixSort(arr, start, end);

    for (int k = start; k <= end; k++) {
        arr[k] *= -1;
    }

    swap(arr, start, end);
}

void sort(int *arr, int n) {
    int i = 0, j = n - 1;
    int negtiveFlag = 0;

    while(i < j) {
        while(i < j && arr[i] < 0) {
            i++;
            if (negtiveFlag == 0) {
                negtiveFlag = 1;
            }
        }
        
        while(i < j && arr[j] >= 0) {
            j--;
        }

        if (i < j) {
            swap(arr, i, j);
        }
    }

   
    if (negtiveFlag == 1) {
        if (i == n - 1) { // all negative
            negativeRadixSort(arr, 0, n-1);
        } else {
            negativeRadixSort(arr, 0, i-1);
            radixSort(arr, i, n - 1);
        }
    } else {
        radixSort(arr, 0, n - 1);
    }
}

void generateArr(int *arr, int len) {
    int temp;
    time_t t;
    /* 初始化随机数发生器 */
    srand((unsigned) time(&t));

    for (int i = 0; i < len; i++) {
        arr[i] = rand();
        temp = rand() % 2;
        if (temp == 0) {
            arr[i] *= -1;
        }
    }
}

int main(int argc, char const *argv[]) {
    int arr[MAX] = {};
    int n = MAX;
    
    long long start, end;

    generateArr(arr, n);

    start = GetTickCount();
    sort(arr, n);
    end = GetTickCount();

    printf("\nstart=%lld\n", start);
    printf("end=%lld\n", end);
    printf("diffTime=%lld\n", end - start);

    // printArr(arr, n);

    return 0;
}